package com.hanggold.jfinal.springboot.lesson1.controller;

import com.hanggold.jfinal.springboot.lesson1.service.LockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 *
 * @author <a href="mailto:sunmch@163.com">smc</a>
 * @date 2021-05-09 08:21
 * @since 1.0.0
 **/
@RestController
@RequestMapping("lock")
public class LockController {

	@Autowired
	private LockService lockService;

	@RequestMapping("common/{name}")
	public Object lock(@PathVariable String name) {
		try {
			System.out.println("请求过来: "+ name+" 线程id: " + Thread.currentThread().getId());
			lockService.lock(name);
			System.out.println("获取锁"+" 线程id: " + Thread.currentThread().getId());
			TimeUnit.SECONDS.sleep(35L);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			System.out.println("释放锁"+" 线程id: " + Thread.currentThread().getId());
			lockService.unlock(name);
//			lockService.unTrylock(name);

		}
		return "lock";
	}

	@RequestMapping("try/{name}")
	public Object tryLock(@PathVariable String name) {

		try {
			System.out.println("try请求过来: "+ name+" 线程id: " + Thread.currentThread().getId());
			boolean lock = lockService.tryLock(name);
			System.out.println("lock: " + lock);
			System.out.println("try获取锁"+" 线程id: " + Thread.currentThread().getId());
			TimeUnit.SECONDS.sleep(35L);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			System.out.println("try释放锁"+" 线程id: " + Thread.currentThread().getId());
//			lockService.unTrylock(name);
			lockService.unlock(name);
		}
		return "trylock";
	}
}
